<?php require_once 'httpFilter.php'; 'conf.php';?>
<?php
	require_once 'dto/AutoReconcileDTO.php';
	require_once 'services/budgetServices.php';
	require_once 'statementparsers/OFXStatementParser.php';
	require_once 'statementparsers/FNBCSVStatementParser.php';
	
	
	$accountId = $_REQUEST["accId"];
	$uploadFileType = $_REQUEST["uploadStatementType"];
	$availableBal = $_REQUEST["availableAmnt"];
	$uploadFileName = $_FILES['transactionFile']['tmp_name'];
	$userId = $_SESSION["userid"];
	$errCode = 0;
	$statementBalance = 0;
	$accountNumber = "";
	
	
	if(strcmp($uploadFileType,"CSV") == 0){
		//hashkey already uses accountId as part of the hash in the csv upload, must keep supporting this to avoid duplicates
		$statement = new FNBCSVStatementParser();
		$statement->accountId = $accountId;
	
		
	}
	else{
		//dont need accountId for hash, so allows single call to accounts table
		$statement = new OFXStatementParser();
	}
	
	//get the statement
	$statement->loadFromFile($uploadFileName);
	
	$bankDetails = (array)$statement->getBankAcctDetails();
	$accountNumber = $bankDetails["AccountNumber"];
	
	//make sure user is uploading for correct acccount
	$con = openDbConnection();
	if(strcmp(getAccountNumberByAcctId($accountId),$accountNumber) == 0){
			
		$errCode = uploadStatement($statement,$accountId,$userId);
	}
	else{
		$errCode = 2;
	}
	
	closeDbConnection($con);
	
	
	
	function getAccountNumberByAcctId($accountId){
		$accountNumber = null;
		$query = "select accNum from account where id =".$accountId;
		error_log($query);
		$result = mysql_query($query);
		if(!$result){
		}
		else{
			$row = mysql_fetch_array($result);
			$accountNumber = $row["accNum"];
		}
		return $accountNumber;
	}
	
	function openDbConnection(){
		$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
		if (!$con) {
			die('Could not connect: ' . mysql_error());
		}
		else{
			mysql_select_db(GlobalConfig::db_name, $con);
		}
		return $con;
	}
	
	
	function closeDbConnection($con){
		mysql_close($con);
	}
	
	
	function getAutoReconciles($userId){
		$query = "select *  from autoreconcile where userid=".$userId;
		error_log($query);
		$result1 = mysql_query($query);
		$autoReconciles = array();
		if (!$result1) {
			//$errCode = 1;
		}
		else{		
			//$autoreconciles = array();			
			while($row = mysql_fetch_array($result1)) {
				try {
					$autoreconcile = new AutoReconcileDTO($row["budgetitemid"], $row["akey"], $row["avalue"]);
					array_push($autoReconciles, $autoreconcile);
				} catch(Exception $e){}
			}		
		}	
		return $autoReconciles;
	}
		
	function uploadStatement($statement,$accountId,$userId){
		
		$statementBalance = $statement->getStatementBalance();
		$availableBal = $statement->getAvailableBalance();
		//We update the statement balance
		$query = "update account set stmtBalance=". $statementBalance .", available=". $availableBal ."  where id= ". $accountId;
		error_log($query);
		$result = mysql_query($query) or die(mysql_error());
		if (!$result) {
			$errCode = 1;
			return $errCode;
		}	

		$autoReconciles = getAutoReconciles($userId);
		
		foreach($statement->getTransactions() as $transaction){			
		
			$autoreconcileFound = false;
			$date = $transaction->getDate();
			$bankref = trim($transaction->getBankRef());
			$hashkey = trim($transaction->getHash());
				
			$query = sprintf("insert into transaction (accountId, date, amount, description, reconciled, categoryId, bankRef, hashkey) values (%d, '%s', %f, '', 0, 0, '%s', '%s')",
			$accountId,
			mysql_real_escape_string($date),
			$transaction->getAmount(),
			mysql_real_escape_string($bankref),
			mysql_real_escape_string($hashkey)
			);
			
			$budgetServices = new BudgetService();
			foreach ($autoReconciles as $autoreconcile){
				//error_log("RECONCILE: ".$bankref ." and ". $autoreconcile->budgetitemid);
				if (strlen(stristr($bankref, $autoreconcile->budgetitemid))>0) {
					error_log("FOUND!!! ---->". $autoreconcile->budgetitemid);
					
					$budgetServices->insertAutoReconcileIntoTransaction($accountId, $date, $transaction->getAmount(), $autoreconcile->value, $bankref, $autoreconcile->key, $hashkey);
					$autoreconcileFound = true;
					break;
				}
			}
	
			if (!$autoreconcileFound){
				if ($bankref != ""){
					error_log($query);
					echo $query;
					$result = mysql_query($query);
				}
			}			
		}
	}	
	
?>
<result>
<code> <?php echo $errCode?> </code>
</result>
